﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace nhCore
{
    /// <summary>
    /// 环境站点，单独设备地址，对应Sensors表及关联Configs
    /// </summary>
    public class DbSensor
    {
        private string type;
        #region Sensors表对应，关联Configs表
        /// <summary>
        /// 设备地址
        /// </summary>
        public byte Address { get; set; }
        /// <summary>
        /// 设备id，云链接时使用
        /// </summary>
        public byte Id { get; set; }

        /// <summary>
        /// 表中的类型，如记录仪
        /// </summary>
        public string Type
        {
            get => type;
            set
            {
                type = value;
                IsCgq = byte.TryParse(Type, out _);
            }
        }

        /// <summary>
        /// 设备名称，如：自动气象站
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 要素配置列表
        /// </summary>
        public List<DbConfig> Configs { get; set; } = new List<DbConfig>();
        #endregion

        /// <summary>
        /// Type可转换为byte则为传感器
        /// </summary>
        public bool IsCgq { get; set; }


        public string Display
        {
            get { return string.Format($"{Name}[{Address.ToString().PadLeft(2, '0')}]"); }
        }

        #region 判断是否在线
        /// <summary>
        /// 记录仪支持多条命令，在这记录最后通讯时间
        /// </summary>
        private DateTime LastCommTime { get; set; }

        /// <summary>
        /// 记录最后一次通讯时间
        /// </summary>
        public void RecordingCommTime()
        {
            LastCommTime = DateTime.Now;
        }

        /// <summary>
        /// 判断设备是否在线
        /// </summary>
        public bool IsOnline => DateTime.Now - LastCommTime < CoreGlobal.OutTime;

        /// <summary>
        /// 在线、离线
        /// </summary>
        public string OnlineState => IsOnline ? "在线" : "离线";
        #endregion

        /// <summary>
        /// 每台设备对应的同步状态
        /// </summary>
        public SyncState SyncState { get; set; } = new SyncState();
    }

    /// <summary>
    /// 同步状态
    /// </summary>
    public class SyncState
    {
        private static readonly int maxFailedSize = 5;

        public int SyncFailedCounts { get; set; }
        public int SyncCounts { get; set; }

        /// <summary>
        /// 判断是否同步失败
        /// </summary>
        /// <returns></returns>
        public bool SyncFaileState()
        {
            return SyncFailedCounts >= maxFailedSize;
        }
        /// <summary>
        /// 设置同步失败
        /// </summary>
        public void SetSyncFailedCountsMax()
        {
            SyncFailedCounts += maxFailedSize;
        }
    }
}
